package com.Tread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ThreadPoolExecutor;

public class ExecutorCompletionServiceTest {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ThreadPoolExecutor poolExecutor = SingleThreadPool.getInstance();

        List<Callable<Integer>> results = new ArrayList<>();

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            results.add(() -> {
                Thread.sleep(finalI * 1000);
                return finalI * 1000;
            });


        }

        ExecutorCompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(poolExecutor);

        for (Callable<Integer> task : results) {
            completionService.submit(task);
        }

        for (int i = 0; i < 5; i++) {
            System.out.println(completionService.take().get());
        }


    }
}
